<template>
  <div class="pr-40">
    <el-form ref="form" key="0" :model="shelfSlotProp" label-width="auto">
      <el-form-item :label="$t('SUB_RACK_NUMBER')">
        <el-input v-model="shelfSlotProp.shelfNum" readonly />
      </el-form-item>
      <!-- 子架数 -->
      <el-form-item :label="$t('SUB_RACK')">
        <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
          <el-tab-pane
            v-for="(item, index) in shelfSlotProp.shelfList"
            :key="index"
            :label="item.shelfName"
            :name="index + ''"
          />
        </el-tabs>
        <div class="flex mb-10">
          <!-- 子架名称 -->
          <el-form-item :label="$t('SUB_RACK_NAME')" label-width="80" class="w-50 pr-10">
            <el-input v-model.trim="currentTabData.shelfName" maxlength="20" />
          </el-form-item>
          <!-- 槽位数 -->
          <el-form-item :key="keyNum" :label="$t('SLOT_NUMBER')" label-width="80" class="w-50">
            <el-input-number
              v-model="currentTabData.slotNum"
              :min="1"
              :max="64"
              @keyup.stop.native="buildSlotList()"
              @change="buildSlotList()"
            />
          </el-form-item>
        </div>
        <el-table
          :data="currentTabData.slotList || []"
          :empty-text="$t('NO_DATA')"
          class="w-100 slot-table"
          border
        >
          <template slot="empty">
            <NullData />
          </template>
          <el-table-column type="index" :label="$t('SLOT')" width="50" />
          <el-table-column :label="$t('SLOT_NAME')">
            <template slot-scope="scope">
              <el-form-item label-width="0">
                <el-input v-model.trim="scope.row.slotName" size="mini" maxlength="20" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('IS_BOARD_ON')">
            <template slot-scope="scope">
              <el-form-item label-width="0">
                <el-select
                  v-model="scope.row.isInsert"
                  size="mini"
                  @change="isInsertChange(scope.row)"
                >
                  <el-option :label="$t('OK_YES')" :value="true" />
                  <el-option :label="$t('OK_NO')" :value="false" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('IS_OPTICAL_BOARD')">
            <template slot-scope="scope">
              <el-form-item label-width="0">
                <el-select
                  v-if="scope.row.isInsert"
                  v-model="scope.row.isLightBoard"
                  size="mini"
                  @change="isLightChange(scope.row)"
                >
                  <el-option :label="$t('OK_YES')" :value="true" />
                  <el-option :label="$t('OK_NO')" :value="false" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 端口容量 -->
          <el-table-column :label="$t('PORT_CAPACITY')">
            <template slot-scope="scope">
              <el-form-item
                v-if="scope.row.isInsert && scope.row.isLightBoard"
                label-width="0"
                :prop="`shelfList.${editableTabsValue}.slotList.${scope.$index}.boardCapacity`"
                :rules="[
                  {
                    required: true,
                    message: $t('ENTER_NAME', { msg: $t('PORT_CAPACITY') }),
                    trigger: 'blur'
                  },
                  {
                    pattern: /(^[0-9]\d*$)/,
                    message: $t('ONLY_INIT'),
                    trigger: ['blur', 'change']
                  },
                  { validator: validatePort, trigger: ['blur', 'change'] }
                ]"
              >
                <el-input
                  v-model="scope.row.boardCapacity"
                  @change="lightBoardCapacityBlur(scope.row)"
                />
                <!-- <el-input-number
                  v-if="scope.row.isInsert && scope.row.isLightBoard"
                  v-model="scope.row.boardCapacity"
                  size="mini"
                  clearable
                  style="width: 100%;"
                  :min="0"
                  :max="128"
                  :controls="true"
                  @keyup.enter.native="lightBoardCapacityBlur(scope.row)"
                  @blur="lightBoardCapacityBlur(scope.row)"
                  @change="lightBoardCapacityBlur(scope.row)"
                /> -->
              </el-form-item></template>
          </el-table-column>
          <el-table-column :label="$t('PORT_INFO')">
            <template v-if="scope.row.netPortList" slot-scope="scope">
              <el-form-item label-width="0">
                <span
                  v-if="scope.row.netPortList && scope.row.isInsert && scope.row.isLightBoard"
                  :disabled="scope.row.netPortList.length === 0"
                  class="portdetailsbtn"
                  @click="showLightBoardPortList(scope.row)"
                >
                  {{ $t('PORT_DETAILS') }}
                </span>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <Portsdetails
      v-if="lightBoardPortLists.netPortList"
      :light-board-port-lists="lightBoardPortLists.netPortList"
      :port-list-visible="portListVisible"
      :biz-port-list="bizPortList"
      :type="type"
      @close="close"
    />
  </div>
</template>

<script>
  import nodeApi from '@/api/oen/NodeApi'
  import Portsdetails from './Portsdetails'

  export default {
    name: 'Shelf',
    components: { Portsdetails },
    props: {
      deviceProp: {
        type: Object,
        default: () => {}
      },
      type: {
        type: String,
        default: 'add'
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        editableTabsValue: 0,
        lightBoardPortLists: {},
        portListVisible: false,
        currentShelf: {},
        bizPortList: {},
        keyNum: 1
      }
    },
    computed: {
      shelfSlotProp() {
        return this.deviceProp.trans
      },
      currentTabData() {
        return this.shelfSlotProp.shelfList[this.editableTabsValue]
      }
    },
    watch: {
      editableTabsValue(newval) {
        this.editableTabsValue = newval + ''
      }
    },
    created() {
      if (this.shelfSlotProp.shelfList.length === 0) {
        this.handleTabsEdit('', 'add')
      } else {
        this.editableTabsValue = 0
      }
      if (this.type === 'mod') {
        this.getPortList()
      }
    },
    methods: {
      getPortList() {
        nodeApi
          .portList({
            nodeId: this.rowData.nodeId,
            status: null
          })
          .then((res = []) => {
            res.forEach(i => {
              this.bizPortList[i.portId] = i.status
            })
          })
      },
      handleTabsEdit(targetIndex, action) {
        const shelfList = this.shelfSlotProp.shelfList
        if (action === 'add') {
          if (shelfList.length >= 32) {
            this.$message(this.$t('SUB_RACK_TIP'))
            return false
          }
          // 增加子架
          let selfIndex = 1
          const shelfcount = shelfList.length
          if (shelfcount !== 0) {
            // 增加子架默认按最后一个的编号=1,selfIndex为新增的 前端临时用 SKS 20220107
            const selfInfo = shelfList[shelfcount - 1]
            selfIndex = selfInfo.selfIndex ? selfInfo.selfIndex + 1 : shelfList.length + 1
          }

          shelfList.push({
            shelfName: this.$t('SUB_RACK') + String(selfIndex), // 子架
            shelfNo: '',
            slotNum: 1,
            slotList: [
              {
                isInsert: true,
                isLightBoard: true,
                boardCapacity: 1,
                netPortList: [
                  {
                    isInsert: true,
                    interfaceType: 'SINGLE',
                    moduleRate: 3,
                    moduleType: 'SINGLE',
                    waveLength: 1
                  }
                ],
                slotName: 'P1',
                slotNo: ''
              }
            ],
            selfIndex: selfIndex
          })
          this.editableTabsValue = shelfcount
        }
        if (action === 'remove') {
          // 删除子架
          console.info('targetIndex', targetIndex, this.editableTabsValue)
          if (shelfList.length === 1) {
            this.$message(this.$t('SUB_RACK_TIP2'))
            return false
          }
          const delshelf = shelfList[targetIndex]
          console.info('delshelf', delshelf)
          if (
            delshelf &&
            delshelf.slotList.some(i =>
              i.netPortList.some(j =>
                j.litPortList.some(
                  k => this.bizPortList[k.portId] && this.bizPortList[k.portId] !== 'IDLE'
                )
              )
            )
          ) {
            this.$message.error(this.$t('BIZPORT_CANNOT_DELETE'))
            return
          }
          if (targetIndex === this.editableTabsValue) {
            this.editableTabsValue = shelfList.length - 1
          }

          shelfList.splice(targetIndex, 1)
          this.editableTabsValue = this.editableTabsValue === '0' ? 0 : this.editableTabsValue - 1
        }
        this.shelfSlotProp.shelfNum = shelfList.length
      },
      /**
       * 是否插板卡 状态修改
       */
      isInsertChange(row) {
        // 1.光板 设置为 false
        row.isLightBoard = false
        // 2. 光板端口容量 设置 初始状态
        row.boardCapacity = ''
        // 3. portList 设置 空数组
        row.netPortList = []
      },
      /**
       * 是否为光板 状态修改
       */
      isLightChange(row) {
        // 1. 光板端口容量 设置 初始状态
        row.boardCapacity = ''
        // 2. portList 设置 空数组
        row.netPortList = []
      },
      // 光板 端口容量
      lightBoardCapacityBlur(row) {
        // 记录已存在端口容量
        const boardCapacity = row.netPortList.length
        // 记录输入的端口容量
        const inputBoardCapacity = row.boardCapacity
        if (inputBoardCapacity > boardCapacity) {
          // 新增
          for (let i = boardCapacity; i < inputBoardCapacity; i++) {
            row.netPortList.push({
              isInsert: true,
              interfaceType: 'SINGLE',
              moduleRate: 3,
              moduleType: 'SINGLE',
              waveLength: 1
            })
          }
        } else {
          const delArr = row.netPortList.slice(inputBoardCapacity, boardCapacity)
          if (
            delArr.some(
              i =>
                i.litPortList &&
                i.litPortList.some(
                  j => this.bizPortList[j.portId] && this.bizPortList[j.portId] !== 'IDLE'
                )
            )
          ) {
            this.$message.error(this.$t('BIZPORT_CANNOT_DELETE'))
            row.boardCapacity = boardCapacity
            return
          }
          row.netPortList = row.netPortList.slice(0, inputBoardCapacity)
        }
      },
      // 显示端口信息
      showLightBoardPortList(row) {
        this.lightBoardPortLists = row
        this.$nextTick(() => {
          if (document.getElementsByClassName('el-message--error').length) return
          this.portListVisible = true
        })
      },
      buildSlotList() {
        // 记录已存在的槽位数
        const slotNum = this.currentTabData.slotList.length
        const lastName = this.currentTabData.slotList[slotNum - 1]['slotName']
        const str = lastName.replace(/[0-9]+/g, '')
        const numList = lastName.match(/\d+/g) || []
        const strnum = numList[0] || 0
        // 记录当前子架输入的槽位数
        const inputSlotNum = this.currentTabData.slotNum
        const len = inputSlotNum - slotNum
        if (slotNum < inputSlotNum) {
          // 新增
          for (let i = 0; i < len; i++) {
            this.currentTabData.slotList.push({
              isInsert: true,
              isLightBoard: true,
              boardCapacity: 1,
              netPortList: [
                {
                  isInsert: true,
                  interfaceType: 'SINGLE',
                  moduleRate: 3,
                  moduleType: 'SINGLE',
                  waveLength: 1
                }
              ],
              slotName: str + (Number(strnum) + (i + 1)),
              slotNo: ''
            })
          }
        } else {
          // 减少槽位数
          if (slotNum - inputSlotNum > 0) {
            const delArr = this.currentTabData.slotList.slice(inputSlotNum, slotNum)
            if (
              delArr.some(i =>
                i.netPortList.some(
                  j =>
                    j.litPortList &&
                    j.litPortList.some(
                      k => this.bizPortList[k.portId] && this.bizPortList[k.portId] !== 'IDLE'
                    )
                )
              )
            ) {
              this.$message.error(this.$t('BIZPORT_CANNOT_DELETE'))
              this.currentTabData.slotNum = slotNum
              this.keyNum++
              return
            }
            for (let i = 0; i < slotNum - inputSlotNum; i++) {
              this.currentTabData.slotList.pop()
            }
          }
        }
      },
      close() {
        this.portListVisible = false
      },
      validatePort(rule, value, callback) {
        if (Number(value) > 128) {
          callback(
            new Error(
              this.$t('PORT_CAPACITY_VALID', {
                msg1: this.$t('PORT_CAPACITY'),
                msg2: 128
              })
            )
          )
        } else if (Number(value) < 1) {
          callback(
            new Error(
              this.$t('PORT_CAPACITY_VALID_MIN', {
                msg1: this.$t('PORT_CAPACITY'),
                msg2: 1
              })
            )
          )
        } else {
          callback()
        }
      }
    }
  }
</script>
